<template>
  <el-dialog
    v-model="internalVisible"
    width="900px"
    :close-on-click-modal="false"
    append-to-body
    modal-append-to-body
    class="unified-dialog report-regenerate-dialog"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-text">
          <h3>再次生成报表</h3>
          <p>
            基于历史运行记录重新生成报表
          </p>
        </div>
        <el-tag type="success" v-if="currentTemplateMeta">{{ currentTemplateMeta.templateName }}</el-tag>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="120px"
      class="report-form"
    >
      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- Tab 1: 基础信息 -->
        <el-tab-pane label="基础信息" name="base">
          <section class="form-section">
            <div class="section-header">
              <el-icon><Document /></el-icon>
              <h4>基础信息</h4>
            </div>
            
            <el-form-item label="报表标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入报表标题"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="模板类型" prop="template_code">
              <el-select
                v-model="form.template_code"
                placeholder="请选择模板"
                :disabled="!!runData"
                @change="handleTemplateChange"
                style="width: 100%"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option-group
                  v-for="group in groupedTemplates"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="template in group.templates"
                    :key="template.template_code"
                    :label="template.template_name"
                    :value="template.template_code"
                  >
                    <span>{{ template.template_name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ template.description }}
                    </span>
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            
            <el-form-item label="输出格式">
              <el-checkbox-group v-model="form.output_formats">
                <el-checkbox label="html">HTML</el-checkbox>
                <el-checkbox label="excel">Excel</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </section>
        </el-tab-pane>

        <!-- Tab 2: 模板参数 -->
        <el-tab-pane label="模板参数" name="template">
          <ReportFormCore
            v-model="form.params"
            :template-code="form.template_code"
            ref="formCoreRef"
            @update:model-value="handleParamsChange"
          />
        </el-tab-pane>

        <!-- Tab 3: SQL 预览 -->
        <el-tab-pane label="SQL 预览" name="sql">
          <ReportSqlPreview
            :template-code="form.template_code"
            :params="form.params"
          />
        </el-tab-pane>

        <!-- Tab 4: 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <NotificationChannelForm
            v-model="notificationForm"
            :webhook-options="webhookOptions"
          />
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          生成报表
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import ReportFormCore from './ReportFormCore.vue'
import NotificationChannelForm from '../shared/NotificationChannelForm.vue'
import ReportSqlPreview from '../shared/ReportSqlPreview.vue'
import { getTemplateMeta, listTemplatesByGroup } from '../templates/registry'
import { buildFormDataFromRun, rebuildTimeRangeForParams } from '../../utils/reportDataLoader'
// @ts-ignore 缺少类型声明的 JS 模块
import api from '@/utils/api'
// @ts-ignore 缺少类型声明的 JS 模块
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ReportRegenerateDialog')

const props = defineProps<{
  modelValue: boolean
  runId: number | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'generated', runId?: string | number): void
}>()

const internalVisible = computed({
  get: () => props.modelValue,
  set: (val: boolean) => emit('update:modelValue', val)
})

const form = reactive({
  template_code: '',
  title: '',
  output_formats: ['html'],
  params: {} as Record<string, any>
})

const notificationForm = reactive({
  send_notification: false,
  channels: [] as string[],
  webhook_id: null as number | null,
  wecom_mentioned_list: '',
  wecom_mentioned_all: false
})

const groupedTemplates = ref<any[]>([])
const webhookOptions = ref<any[]>([])
const submitting = ref(false)
const loading = ref(false)
const runData = ref<any>(null)
const activeTab = ref('base')
const formRef = ref()
const formCoreRef = ref()

const currentTemplateMeta = computed(() => {
  if (!form.template_code) return null
  return getTemplateMeta(form.template_code)
})

const formRules = {
  template_code: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ]
}

const resetForm = () => {
  form.template_code = ''
  form.title = ''
  form.output_formats = ['html']
  form.params = {}
  notificationForm.send_notification = false
  notificationForm.channels = []
  notificationForm.webhook_id = null
  notificationForm.wecom_mentioned_list = ''
  notificationForm.wecom_mentioned_all = false
  runData.value = null
}

const fetchTemplates = async () => {
  try {
    const response = await api.get('/reports/templates', { params: { page: 1, size: 1000 } })
    const rows = response.data.data?.rows || []
    const mappedCodes = new Set<string>()
    const registryGroups = listTemplatesByGroup()
      .map((group) => ({
        ...group,
        templates: group.templates
          .map((tpl) => {
            const remote = rows.find((row: any) => row.template_code === tpl.templateCode)
            if (remote) mappedCodes.add(remote.template_code)
            return {
              template_code: tpl.templateCode,
              template_name: remote?.template_name || tpl.templateName,
              description: remote?.description || tpl.description
            }
          })
          .filter(Boolean)
      }))
      .filter((group) => group.templates.length > 0)

    const fallback = rows
      .filter((row: any) => !mappedCodes.has(row.template_code))
      .map((row: any) => ({
        template_code: row.template_code,
        template_name: row.template_name,
        description: row.description
      }))

    groupedTemplates.value = [
      ...registryGroups,
      ...(fallback.length > 0 ? [{ label: '其他', templates: fallback }] : [])
    ]
  } catch (error) {
    componentLogger.error('获取模板列表失败', error)
    ElMessage.error('获取模板列表失败')
  }
}

const fetchWebhooks = async () => {
  try {
    // 暂时注释掉webhook获取，因为接口不存在
    // const response = await api.get('/webhooks')
    // webhookOptions.value = response.data.data?.rows || []
    webhookOptions.value = []
  } catch (error) {
    componentLogger.warn('获取Webhook列表失败，使用空列表', error)
    webhookOptions.value = []
  }
}

const loadRunDetail = async (runId: number) => {
  loading.value = true
  try {
    const response = await api.get(`/reports/runs/${runId}`)
    const data = response.data.data
    
    if (!data) {
      ElMessage.error('未找到运行记录')
      return
    }
    
    runData.value = data
    
    // 构建表单数据
    const formData = await buildFormDataFromRun(data, api)
    
    // 设置表单数据
    form.template_code = formData.template_code
    form.title = formData.title
    form.output_formats = formData.output_formats
    form.params = rebuildTimeRangeForParams(formData.params)
    
    // 设置通知参数
    if (formData.notify_params) {
      const np = formData.notify_params
      notificationForm.send_notification = np.send_notification || false
      notificationForm.channels = np.channels || []
      notificationForm.webhook_id = np.webhook_id || null
      
      // 处理企业微信通知
      if (np.wecom_mention) {
        const wm = typeof np.wecom_mention === 'string' ? JSON.parse(np.wecom_mention) : np.wecom_mention
        notificationForm.wecom_mentioned_all = Boolean(wm.is_all)
        if (wm.to_user && wm.to_user.length > 0) {
          notificationForm.wecom_mentioned_list = wm.to_user.join(',')
        }
      }
    }
    
    componentLogger.info('加载运行记录成功', { runId, template_code: form.template_code })
  } catch (error) {
    componentLogger.error('加载运行记录失败', error)
    ElMessage.error('加载运行记录失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const handleTemplateChange = () => {
  // 模板变化时，重置参数
  if (!runData.value) {
    // 只有在非编辑模式下才重置参数
    const meta = getTemplateMeta(form.template_code)
    if (meta?.defaultParams) {
      form.params = { ...meta.defaultParams }
    } else {
      form.params = {}
    }
  }
}

const handleParamsChange = (params: Record<string, any>) => {
  form.params = params
}

const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate()
    
    // 验证模板参数
    if (formCoreRef.value) {
      const formCoreValid = await formCoreRef.value.validate()
      if (!formCoreValid) {
        activeTab.value = 'template'
        ElMessage.error('请检查模板参数配置')
        return
      }
    }
    
    submitting.value = true
    
    // 构建通知参数
    let notifyParams: any = null
    if (notificationForm.send_notification) {
      notifyParams = {
        send_notification: true,
        channels: notificationForm.channels
      }
      
      // 添加Webhook配置
      if (notificationForm.webhook_id) {
        notifyParams.webhook_id = notificationForm.webhook_id
      }
      
      // 添加企业微信@配置
      if (notificationForm.channels.includes('wecom')) {
        const wecomMention: any = { is_all: notificationForm.wecom_mentioned_all }
        if (!notificationForm.wecom_mentioned_all && notificationForm.wecom_mentioned_list) {
          wecomMention.to_user = notificationForm.wecom_mentioned_list
            .split(',')
            .map((id: string) => id.trim())
            .filter(Boolean)
        }
        notifyParams.wecom_mention = wecomMention
      }
    }
    
    // 提交生成请求
    const response = await api.post('/reports/generate', {
      template_code: form.template_code,
      title: form.title,
      params: form.params,
      output_formats: form.output_formats,
      notify_params: notifyParams
    })
    
    if (response.data.success) {
      ElMessage.success('报表生成任务已提交')
      emit('generated', response.data.data?.run_id)
      internalVisible.value = false
    } else {
      ElMessage.error(response.data.message || '生成失败')
    }
  } catch (error) {
    componentLogger.error('生成报表失败', error)
    ElMessage.error('生成报表失败：' + (error.response?.data?.message || error.message))
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  internalVisible.value = false
}

// 监听对话框可见性
watch(() => internalVisible.value, async (visible) => {
  if (visible) {
    // 对话框打开时
    await Promise.all([
      fetchTemplates(),
      fetchWebhooks()
    ])
    
    if (props.runId) {
      await loadRunDetail(props.runId)
    } else {
      resetForm()
    }
  } else {
    // 对话框关闭时重置表单
    resetForm()
  }
})

// 监听 runId 变化（仅在对话框已打开且 runId 真正变化时）
watch(() => props.runId, async (newId, oldId) => {
  if (internalVisible.value && newId && newId !== oldId) {
    await loadRunDetail(newId)
  }
})
</script>

<style scoped>
.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.header-text h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-text p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 14px;
}

.config-tabs {
  margin-top: 20px;
}

.form-section {
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header .el-icon {
  font-size: 18px;
  color: #409eff;
  margin-right: 8px;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.report-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.report-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

.report-form :deep(.el-input__inner) {
  border-radius: 8px;
}

.report-form :deep(.el-select) {
  width: 100%;
}

.report-form :deep(.el-checkbox-group) {
  display: flex;
  gap: 16px;
}
</style>
